//
//  ASOBAudioBookViewController.m
//  ASOBAudioBook
//
//  Created by Staffan Persson on 30/07/2011.
//  Copyright 2011 Know IT Stockholm AB. All rights reserved.
//

#import "ASOBAudioBookViewController.h"

@interface ASOBAudioBookViewController()

- (void)getTracks:(NSMutableArray *)arguments;
- (void)commandExecuteRequest:(NSURLRequest *)asobAudioRequest;

@end

@implementation ASOBAudioBookViewController

static MPMusicPlayerController *appMusicPlayer;
static NSArray *listedTracks;

@synthesize webView;

#pragma mark - ASOBAudio methods

- (void)webLog:(NSMutableArray *)arguments {
    for (NSString *log in arguments) {
        NSLog(@"Web log: %@", log);
    }
}

- (void)commandExecuteRequest:(NSURLRequest *)asobAudioRequest {    
    // Execute commands
    [webView stringByEvaluatingJavaScriptFromString:@"ASOBAUDIO.iOSBridge.runningCommands = true;"];
    
    // Grab all the queued commands from the JS side.
    NSString *jsonString = [webView stringByEvaluatingJavaScriptFromString:@"ASOBAUDIO.iOSBridge.getAndClearQueuedCommands();"];
    //NSLog(@"commandsJSON: %@", jsonString);
    
    // An empty array has a string length of two, '[]'
    while ([jsonString length] > 2) {
        // Parse the returned JSON array.
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        // JSONSerializer
        id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        
        if (error == nil) {
            // Expecting an array.
            NSArray *commands = (NSArray *) jsonObject;
            // Iterate over and execute all of the commands.
            for (NSString *commandJson in commands) {
                //NSLog(@"commandJson: %@", commandJson);
                    
                // Expecting a dictionary.
                NSDictionary *commandDict = [NSJSONSerialization 
                                             JSONObjectWithData:[commandJson dataUsingEncoding:NSUTF8StringEncoding] 
                                             options:0 
                                             error:&error];
                if (error == nil) {
                    ServiceCommand *command = [ServiceCommand initWithDictionary:commandDict];
                    NSString* fullMethodName = [[NSString alloc] initWithFormat:@"%@:", command.service];
                    if ([self respondsToSelector:NSSelectorFromString(fullMethodName)]) {
                        [self performSelector:NSSelectorFromString(fullMethodName) withObject:command.arguments];
                    } else {
                        // There's no method to call, so throw an error.
                        NSLog(@"ERROR: Method '%@' not defined.", fullMethodName);
                    }
                } else {
                    NSLog(@"JSON parsing error: %@", [error localizedDescription]);
                }
            }
        } else {
            NSLog(@"JSON parsing error: %@", [error localizedDescription]);
        }
        
        // Check for new commands
        jsonString = [webView stringByEvaluatingJavaScriptFromString:@"ASOBAUDIO.iOSBridge.getAndClearQueuedCommands();"];
    }
    [webView stringByEvaluatingJavaScriptFromString:@"ASOBAUDIO.iOSBridge.runningCommands = false;"];
}

#pragma mark - Media methods

- (void)getTracks:(NSMutableArray *)arguments {
    MPMediaQuery *query = [MPMediaQuery audiobooksQuery];
    listedTracks = [query items];
    NSMutableString *tracksJsonArr = [[NSMutableString alloc] initWithString: @"["];
    NSInteger i = 0;
    NSString *jsonStrTemp = @"\"%@\"";
    NSString *author, *book, *mediaId, *title;
    NSMutableString *jsonObject;
    for (MPMediaItem *track in listedTracks) {
        // Track properties.
        mediaId = [[NSString alloc] initWithFormat:jsonStrTemp, [track valueForProperty:MPMediaItemPropertyPersistentID]];
        title = [[NSString alloc] initWithFormat:jsonStrTemp, [track valueForProperty:MPMediaItemPropertyTitle]];
        book = [[NSString alloc] initWithFormat:jsonStrTemp, [track valueForProperty:MPMediaItemPropertyAlbumTitle]];
        author = [[NSString alloc] initWithFormat:jsonStrTemp, [track valueForProperty:MPMediaItemPropertyArtist]];
        
        // Create JSON object.
        jsonObject = [[NSMutableString alloc] initWithFormat:@"{"];
        [jsonObject appendFormat:@"\"mediaId\" : %@,", mediaId];
        [jsonObject appendFormat:@"\"author\" : %@,", author];
        [jsonObject appendFormat:@"\"book\" : %@,", book];
        [jsonObject appendFormat:@"\"title\" : %@", title];
        [jsonObject appendString:@"},"];
        
        // Add object to JSON array.
        [tracksJsonArr appendString:jsonObject];
        
        // Limit data for test.
        i++;
        if (i == 5) {
            NSLog(@"TEST getTracks: Data limited for testing purposes.");
            break;
        }
        
    }
    if (tracksJsonArr.length > 1) {
        // Remove last comma.
        [tracksJsonArr deleteCharactersInRange:NSMakeRange([tracksJsonArr length] - 1, 1)];
    }
    [tracksJsonArr appendString:@"]"];
    NSLog(@"tracks string: %@", tracksJsonArr);
    [webView stringByEvaluatingJavaScriptFromString:[[NSString alloc] 
                                                     initWithFormat:@"ASOBAUDIO.libraryUtils.setTracksFromMediaLibrary(%@);", tracksJsonArr]];
}

#pragma mark - UIWebViewDelegate

//Catch ASOBAudioBook requests via the asobaudio scheme.
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType) navigationType {
    if ([[[request URL] scheme] isEqualToString:@"asobaudio"]) {
        [self commandExecuteRequest:request];
        return NO;
    }
    return YES;
}

#pragma mark - Memory management

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Web view
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"medialist" ofType:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:resourcePath]];
    [webView loadRequest:request];
    
    // Music player
    appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end
    